//
//  UIImage+Helper.swift
//  SwiftWeibo
//
//  Created by suqianghotel on 16/11/19.
//  Copyright © 2016年 suqianghotel. All rights reserved.
//

import Foundation
import UIKit


extension UIImage
{
    func horizonResize() -> UIImage {
        return resizableImage(withCapInsets: UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5), resizingMode: .tile)
    }
    
    func verticalResize() -> UIImage {
        return resizableImage(withCapInsets: UIEdgeInsets(top: 5, left: 0, bottom: 5, right: 0), resizingMode: .tile)
    }
    
    
    func resize() -> UIImage {
        return resizableImage(withCapInsets: UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5), resizingMode: .tile)
    }
    
    func tile() -> UIImage {
        return resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .tile)
    }
    
    
    func sq_circleImage(size:CGSize?, backgroundColor:UIColor=UIColor.white, isCircle:Bool=false) -> UIImage {
        
        
        var size = size
        
        if size == nil || size?.width == 0 || size?.height == 0 {
            size = self.size
        }
        

        let minValue = min(size!.width, size!.height)
        
        let newSize = CGSize(width: minValue, height: minValue)
        
        
        UIGraphicsBeginImageContextWithOptions(newSize, true, 0)
        
        let rect = CGRect(origin: CGPoint(), size: newSize)
        
        backgroundColor.setFill()
        
        UIRectFill(rect)
        
        if isCircle {
            
            let path = UIBezierPath(ovalIn: rect)
            
            path.addClip()
        }
        
        self.draw(in: rect)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        
        return image ?? self
        
    }
    
    
    
    func sq_image(size:CGSize, backgroundColor:UIColor?=UIColor.white) -> UIImage {
        
        UIGraphicsBeginImageContextWithOptions(size, true, 0)
        
        let rect = CGRect(origin: CGPoint(), size: size)
        
        UIRectFill(rect)
        
        backgroundColor?.setFill()
        
        self.draw(in: rect)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        
        return image ?? self
        
    }
    
    
    
    
}
